<template>
  <div class="app-container">
    <div class="search">
      <!-- 搜索表单 -->
      <el-form :model="serchForm" ref="formRef">
        <el-row :gutter="20">
          <el-col :span="8"
            ><div class="grid-content ep-bg-purple" />
            <el-form-item label="应用名称" prop="account">
              <el-input
                v-model="serchForm.model.appName"
                placeholder="请输入应用名称"
                style="width: 200px"
              ></el-input> </el-form-item
          ></el-col>

          <el-col :span="8"
            ><div class="grid-content ep-bg-purple" />
            <el-form-item label="购买账号" prop="account">
              <el-input
                v-model="serchForm.model.purchaseAccount"
                placeholder="购买账号"
                style="width: 200px"
              ></el-input> </el-form-item
          ></el-col>

          <el-col :span="8">
            <el-form-item label="授权状态">
              <el-select
                v-model="serchForm.model.status"
                placeholder="请选择"
                size="mini"
              >
                <el-option label="有效" :value="1"></el-option>
                <el-option label="无效" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8"
            ><div class="grid-content ep-bg-purple" />
            <el-form-item label="创建时间" prop="createAt">
              <el-date-picker
                v-model="serchForm.createAt"
                type="daterange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间" /></el-form-item
          ></el-col> -->
        </el-row>
      </el-form>
      <!--重置 搜搜按钮 -->
      <div class="btns">
        <el-button icon="Refresh" @click="handleResetClick">重置</el-button>
        <el-button type="primary" icon="Search" @click="handleQueryClick"
          >查询</el-button
        >
        <el-button type="primary" @click="add"
          ><el-icon><Upload /></el-icon>新增</el-button
        >
      </div>
    </div>

    <!-- 表单 -->
    <div class="content">
      <div class="content">
        <div class="table">
          <el-table :data="dataList" border style="width: 100%">
            <el-table-column
              align="center"
              prop="id"
              label="序号"
              width="80px"
            />
            <el-table-column
              align="center"
              prop="appName"
              label="应用名称 "
              width="150"
            />

            <el-table-column
              align="center"
              prop="purchaseAccount"
              label="购买账号"
            />
            <el-table-column
              align="center"
              prop="accountName"
              label="购买账号名称"
            />
            <el-table-column
              align="center"
              prop="transactionTime"
              label="成交时间"
              width="180"
            />
            <el-table-column
              align="center"
              prop="usagePeriod"
              label="使用期限"
            />
            <el-table-column
              align="center"
              prop="expirationTime"
              label="到期时间"
              show-overflow-tooltip
            />
            <!-- <el-table-column
              align="center"
              prop="createTime"
              label="申请时间"
              width="200"
            >
              <template #default="scope">
                {{ formatDateTime(scope.row.createTime) }}
              </template>
            </el-table-column> -->
            <el-table-column
              align="center"
              prop="contactStatus"
              label="授权状态"
              width="100"
            >
              <template #default="scope">
                <el-switch
                  v-model="scope.row.status"
                  :active-value="1"
                  :inactive-value="0"
                  @click="changeShow(scope.row)"
                />
              </template>
            </el-table-column>

            <el-table-column align="center" label="操作" width="240">
              <template #default="scope">
                <el-row>
                  <el-button
                    size="small"
                    type="primary"
                    text
                    @click="handelEdit(scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    size="small"
                    type="primary"
                    text
                    @click="handelOpenDetail(scope.row)"
                    >查看</el-button
                  >

                  <el-popconfirm
                    placement="bottom"
                    title="确认删除吗?"
                    trigger="click"
                    @confirm="handelApproved(scope.row)"
                  >
                    <template #reference>
                      <el-button type="danger" size="small" text
                        >删除</el-button
                      >
                    </template>
                  </el-popconfirm>

                  <!-- <el-button type="primary" size="small" text>查看</el-button> -->
                </el-row>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <el-pagination
            v-model:current-page="serchForm.current"
            v-model:page-size="serchForm.size"
            :page-sizes="[10, 20, 30]"
            layout="->,total,sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="title" @close="close">
      <el-form :model="form" :rules="rules" ref="formEl" :disabled="view">
        <el-form-item label="应用名称" label-width="110" prop="appName">
          <!-- <el-input
            v-model="form.appName"
            autocomplete="off"
            placeholder="请输入应用名称"
          /> -->

          <el-select
            style="width: 100%"
            v-model="form.appName"
            filterable
            remote
            reserve-keyword
            placeholder="输入关键字选择"
            :remote-method="remoteMethod"
            :loading="loading"
            @change="appNameChange"
          >
            <el-option
              v-for="item in options1"
              :key="item.id"
              :label="item.appName"
              :value="item.appName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="购买账号" label-width="110" prop="purchaseAccount">
          <!-- <el-input
            v-model="form.purchaseAccount"
            autocomplete="off"
            placeholder="请输入购买账号"
          /> -->
          <el-select
            style="width: 100%"
            v-model="form.purchaseAccount"
            filterable
            remote
            reserve-keyword
            placeholder="输入关键字选择"
            :remote-method="remoteMethod2"
            :loading="loading"
            @change="userChange"
          >
            <el-option
              v-for="item in options2"
              :key="item.id"
              :label="item.userName"
              :value="item.userName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="购买账号名称" label-width="110" prop="accountName">
          <el-input
            disabled
            v-model="form.accountName"
            autocomplete="off"
            placeholder="请选择购买账号自动填入对应名称"
          />
        </el-form-item>
        <el-form-item label="成交时间" label-width="110" prop="transactionTime">
          <el-date-picker
            v-model="form.transactionTime"
            type="datetime"
            placeholder="成交时间"
            format="YYYY/MM/DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
            @change="validateDateRange('transactionTime')"
          />
        </el-form-item>
        <el-form-item label="使用期限" label-width="110" prop="usagePeriod">
          <el-input v-model="form.usagePeriod" autocomplete="off" />
        </el-form-item>
        <el-form-item label="到期时间" label-width="110" prop="expirationTime">
          <el-date-picker
            v-model="form.expirationTime"
            type="datetime"
            placeholder="到期时间"
            format="YYYY/MM/DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
            @change="validateDateRange('expirationTime')"
          />
        </el-form-item>
        <el-form-item label="授权状态" label-width="110" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer" v-if="!view">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import { rules } from "./rules";
import { formatDateTime } from "@/utils/index.js";
import {
  queryListRequest,
  addRequest,
  editRequest,
  deleteRequest,
  searchAppNameRequest,
  searchuserNameRequest,
} from "@/api/appStore/dealrecord.js";
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();

onMounted(() => {
  if (route.query.appName) {
    form.appName = route.query.appName;
    form.appId = route.query.appId;
    dialogFormVisible.value = true;
  }
});

const total = ref(0);

const view = ref(false);

const loading = ref(false);
const options1 = ref([]);
const options2 = ref([]);
const remoteMethod = (query) => {
  if (query) {
    loading.value = true;
    searchAppNameRequest({ appName: query }).then((res) => {
      options1.value = res.data;
      loading.value = false;
    });
  } else {
    options1.value = [];
  }
};
const remoteMethod2 = (query) => {
  if (query) {
    loading.value = true;
    searchuserNameRequest({ userName: query }).then((res) => {
      options2.value = res.data;
      loading.value = false;
    });
  } else {
    options2.value = [];
  }
};
const userChange = (value) => {
  console.log(value);
  let res = options2.value.find((item) => {
    //判断item.userName和value值相等的 返回其 nickName
    if (item.userName === value) {
      return item;
    }
  });
  form.accountName = res.nickName;
};

let title = ref("");

const serchForm = reactive({
  current: 1,
  size: 10,
  model: {
    appName: "",
    purchaseAccount: "",
    status: "",
  },
});

onMounted(() => {
  getList();
});

const validateDateRange = (name) => {
  if (form.transactionTime > form.expirationTime && form.expirationTime) {
    ElMessage.warning("成交时间不能大于到期时间");
    form[name] = "";
    return false;
  }
  return true;
};

const add = () => {
  dialogFormVisible.value = true;
  title.value = "新增";
};

// 列表数据
const dataList = ref([]);
async function getList() {
  const res = await queryListRequest(serchForm);
  console.log(res);
  dataList.value = res.data.records;
  total.value = res.data.total;
}

//重置
function handleResetClick() {
  console.log("reset");
  serchForm.current = 1;
  serchForm.size = 10;
  serchForm.model = {
    appName: "",
    purchaseAccount: "",
    status: "",
  };
  getList();
}
//查询操作
function handleQueryClick() {
  serchForm.current = 1;
  console.log("handleQueryClick", serchForm);
  getList();
}

//分页器size事件
const handleSizeChange = (size) => {
  serchForm.size = size;
  getList();
};
//分页器current事件
const handleCurrentChange = (current) => {
  serchForm.current = current;
  getList();
};

//状态改版事件
async function changeShow(row) {
  const { status, id } = row;
  const data = {
    id,
    status,
  };
  const res = await editRequest(data);
  console.log(res);
  if (res.code == 200) {
    ElMessage.success("状态修改成功！");
    getList();
  }
}

//编辑操作
const handelEdit = (row) => {
  dialogFormVisible.value = true;
  title.value = "编辑";
  console.log(row);
  form.id = row.id;
  form.appName = row.appName;
  form.appId = row.appId;
  form.purchaseAccount = row.purchaseAccount;
  form.accountName = row.accountName;
  form.transactionTime = row.transactionTime;
  form.usagePeriod = row.usagePeriod;
  form.expirationTime = row.expirationTime;
  form.status = row.status;
};

const handelOpenDetail = (row) => {
  title.value = "详情";
  view.value = true;
  dialogFormVisible.value = true;
  form.appName = row.appName;
  form.appId = row.appId;
  form.purchaseAccount = row.purchaseAccount;
  form.accountName = row.accountName;
  form.transactionTime = row.transactionTime;
  form.usagePeriod = row.usagePeriod;
  form.expirationTime = row.expirationTime;
  form.status = row.status;
};

const close = () => {
  formEl.value.resetFields();
  view.value = false;
  form = reactive({
    appName: "",
    appId: "",
    purchaseAccount: "",
    accountName: "",
    transactionTime: "",
    usagePeriod: "",
    expirationTime: "",
    status: 1,
  });
};

//新增编辑dialog
let dialogFormVisible = ref(false);
let form = reactive({
  appName: "",
  appId: "",
  purchaseAccount: "",
  accountName: "",
  transactionTime: "",
  usagePeriod: "",
  expirationTime: "",
  status: 1,
});
const formEl = ref(null);
//提交表单
const submitForm = () => {
  formEl.value.validate(async (valid, fields) => {
    if (valid) {
      console.log(valid);
      console.log(form);

      if (!form.id) {
        //新增
        const res = await addRequest(form);
        if (res.data) {
          ElMessage.success("新增成功");
          dialogFormVisible.value = false;
          getList();
        }
      } else {
        const res = await editRequest(form);
        if (res.data) {
          ElMessage.success("编辑成功");
          dialogFormVisible.value = false;
          getList();
        }
      }
    } else {
      console.log(fields);
    }
  });
};

//删除
const handelApproved = async (row) => {
  console.log(row);
  const res = await deleteRequest(row.id);
  if (res.data) {
    ElMessage.success("删除成功");
    getList();
  }
};

//应用选择改变
const appNameChange = (value) => {
  console.log(value);
  console.log(options1.value);
  let res = options1.value.find((item) => {
    //判断item.userName和value值相等的 返回其 nickName
    if (item.appName === value) {
      return item.id;
    }
  });
  console.log(res.id);
  form.appId = res.id;
};
</script>
<style scoped>
label {
  font-weight: 0 !important;
}
.search {
  background-color: #fff;
  padding: 20px;
}
.search .btns {
  text-align: right;
  padding: 0 50px 10px 0;
}
.pagination {
  margin-top: 14px;
}
</style>
